gpt4 book ai didi

asp.net-web-api - mvc webapi 跨域发布

转载 作者:行者123 更新时间:2023-12-02 19:40:45 24 4
gpt4 key购买 nike

Possible Duplicate:
CORS with WebAPI for XmlHttpRequest



我正在尝试对我的 webApi 项目实现跨域 ajax post。我对此遇到了一些麻烦:
1. 我总是收到 204 错误,直到将我的 webapi 操作从

public void submit(Submission model)

public bool submit(Submission model)

不知道为什么,但现在我得到 200 OK状态

2.仍然是我的ajax触发错误回调。

3.很久以前我通过添加解决了这种跨域发帖的错误

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

到我的 Controller 。但现在在 webApi 中我是固有的 : ApiController 而且这个伎俩不起作用。显示编译器 Error an object reference is required for the non-static field, method, or property"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...");        }    });

What I'm doing wrong?

SOLVED

Thanks to everybody for helping me out. I found solution in one of the comment links. I used following approach, which I find pretty simple.

Source:
Implementing CORS support in ASP.NET Web APIs


What I made:

1. Created new Class in my project: CorsHandler.cs and just copy-pasted following code:


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 中处理“成功”和“错误”回调。

    最佳答案

    分别回答您的问题:

    1. 状态 204 不是错误,这意味着没有内容可返回,但一切正常。这是 RFC2616 中 204 的定义

    10.2.5 204 No Content

    The server has fulfilled the request but does not need to return anentity-body, and might want to return updated metainformation. Theresponse MAY include new or updated metainformation in the form ofentity-headers, which if present SHOULD be associated with therequested variant.

    If the client is a user agent, it SHOULD NOT change its document viewfrom that which caused the request to be sent. This response isprimarily intended to allow input for actions to take place withoutcausing a change to the user agent's active document view, althoughany new or updated metainformation SHOULD be applied to the documentcurrently in the user agent's active view.

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

  • 您能具体说明您遇到的错误是什么吗? ASP.NET Web API 目前没有现成的 JSONP 格式化程序。这是第三部分的一些实现:
  • 在 Web API 中,引用 Response 的方式不是通过 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-web-api - mvc webapi 跨域发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13018020/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com