How do I modify my Web API server code to add a Access-Control-Allow-Origin' header?

心已入冬 提交于 2019-12-06 14:33:13
artfuldev

From here, I see that there are simple ways with ASP.NET MVC/Web API.

For ASP.NET Web API

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

So now you have defined what an AllowCrossSiteJson Action Filter Attribute means. The rest is just a matter of adding the Action Filter Attribute to the controllers or methods of your choice.

Tag a whole API controller:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

Or individual API calls:

[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
    ...
}

You could also restrict the CORS implementation to your selection of trusted sites. You should just change the "*" to "http://your-domain.com,http://your-domain-2.com" etc. Note the comma separation and the inclusion of the protocol (http:// or https://) in the origin specification. If you are providing localhost, make sure the port number is included.

Hope that helps! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!