asp.net-web-api – mvc webapi cross domain post

前端之家收集整理的这篇文章主要介绍了asp.net-web-api – mvc webapi cross domain post前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Possible Duplicate:
07000


我正在尝试在我的webApi项目中实现跨域ajax文章.我几乎没有麻烦:
我一直在得到204错误,直到更改了我的webapi操作

public void submit(Submission model)

public bool submit(Submission model)

不知道为什么,但现在我得到200 OK状态
还是我的ajax发射错误回调.
很久以前,我通过添加解决了这种跨域发布的错误

HttpContext.Response.AddHeader("Access-Control-Allow-Origin","*");

给我的控制器但现在在webApi我固有的:ApiController和这个技巧不起作用.显示编译器错误对象引用是非静态字段,方法属性“System.Web.HttpContext.Response.get”所必需的
我尝试通过dataType:’JSONP’发布,但是我得到空模型.
这里是Javascript请求:

var model = {
        "type": $("#model-type").val(),"subject": $("#subject-text").val(),"body": $("#body-text").val()
    };

    $.ajax({
        type: "POST",dataType: 'JSONP',url: $("#submit-url").val(),data: model,success: function () {
            alert("Succesfully submitted");
        },error: function () {
            alert("Error...");
        }
    });

我做错了什么?

解决

感谢大家帮助我.我在一个评论链接中找到了解决方案.我使用以下方法,我觉得很简单.
资源:
Implementing CORS support in ASP.NET Web APIs

我做了什么
1.在我的项目中创建新的类:CorsHandler.cs,只是复制粘贴以下代码

public class CorsHandler : DelegatingHandler
    {
        const string Origin = "Origin";
        const string AccessControlRequestMethod = "Access-Control-Request-Method";
        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

        protected override Task SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
        {
            bool isCorsRequest = request.Headers.Contains(Origin);
            bool isPreflightRequest = request.Method == HttpMethod.Options;
            if (isCorsRequest)
            {
                if (isPreflightRequest)
                {
                    return Task.Factory.StartNew(() =>
                    {
                        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add(AccessControlAllowOrigin,request.Headers.GetValues(Origin).First());

                        string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                        if (accessControlRequestMethod != null)
                        {
                            response.Headers.Add(AccessControlAllowMethods,accessControlRequestMethod);
                        }

                        string requestedHeaders = string.Join(",",request.Headers.GetValues(AccessControlRequestHeaders));
                        if (!string.IsNullOrEmpty(requestedHeaders))
                        {
                            response.Headers.Add(AccessControlAllowHeaders,requestedHeaders);
                        }

                        return response;
                    },cancellationToken);
                }
                else
                {
                    return base.SendAsync(request,cancellationToken).ContinueWith(t =>
                    {
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(AccessControlAllowOrigin,request.Headers.GetValues(Origin).First());
                        return resp;
                    });
                }
            }
            else
            {
                return base.SendAsync(request,cancellationToken);
            }
        }
    }

>打开我的Global.asax并修改Application_Start:

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
        }

注意行动的最后一行.
方法与MVC3和.NET 4.0兼容.工作很好,现在我可以处理ajax中的“成功”和“错误”回调.

解决方法

分别回答你的问题:

>状态204不是错误,这意味着没有内容可以返回,但一切都很好.这是RFC2616中的204的定义

10.2.5 204 No Content

The server has fulfilled the request but does not need to return an
entity-body,and might want to return updated Metainformation. The
response MAY include new or updated Metainformation in the form of
entity-headers,which if present SHOULD be associated with the
requested variant.

If the client is a user agent,it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent’s active document view,although
any new or updated Metainformation SHOULD be applied to the document
currently in the user agent’s active view.

The 204 response MUST NOT include a message-body,and thus is always
terminated by the first empty line after the header fields.

>你能说清楚你遇到的错误是什么ASP.NET Web API目前没有JSONP格式化程序.这里有第三部分实现:

> http://www.west-wind.com/weblog/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API
> http://www.nuget.org/packages/WebApi.JsonP
我希望他们有所帮助.

>在Web API中,您引用响应的方式不是通过HttpContext.有多种访问方式.

第一个选项是直接定义动作返回HttpResponse.

public HttpResponseMessage Get(int id)
    {
        var response = this.Request.CreateResponse();
        response.StatusCode = HttpStatusCode.OK;
        response.Headers.Add("Access-Control-Allow-Origin","*");

        return response;
    }

第二个选项是使用ActionFilter:

// define action filter for cross domain
public class CrossDomainActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        bool needCrossDomain = true;

        if (needCrossDomain)
        {
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin","*");
        }

        base.OnActionExecuted(actionExecutedContext);
    }
}

// At Controller
// GET api/values/5
[CrossDomainActionFilter]
public string Get(int id)
{
    return "value";
}

最后一个选项是使用MessageHandler

public class CrossDomainMessageHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request,cancellationToken);
        response.Headers.Add("Access-Control-Allow-Origin","*");

        return response;
    }
}

猜你在找的asp.Net相关文章