Currently we create a website using MVC and data layer we would like to use web api and host in different web server.
I meant the website host on one web server, web api will host on another server. We tried to make a call (like asmx service) to manipulate data from Web Api. We tried to use Ajax but could not make it success. And could not find any
sample for this or using Httpclient inside mvc site. I’m new for web api. If I’m wrong please correct me. Is there somebody could help me? The following code host on server
http://test1/test
@{
ViewBag.Title =
"Home Page";
}
<
scripttype="text/javascript">
function
GetAll() {
jQuery.support.cors =
true;
$.ajax({
url:
'http://tes2.test.com/API/api/crmconsts',
type:
'GET',
dataType:
'json',
success:
function
(data) {
WriteResponse(data);
},
error:
function
(x, y, z) {
alert(x +
'\n'
+ y + '\n' + z);
}
});
}
function
AddConsts() {
jQuery.support.cors =
true;
var
CRMConsts = {
ID:$(
'#id').val(),
OrderBy: $(
'#OrderBy').val(),
ConstType: $(
'#ConstType').val(),
ConstCode: $(
'#ConstCode').val(),
Detail: $(
'#Detail').val(),
Status: $(
'#Status').val()
};
$.ajax({
url:
'http://tes2.test.com/API/api/crmconsts',
type:
'POST',
data: JSON.stringify(CRMConsts),
contentType:
"application/json;charset=utf-8",
success:
function
(data) {
WriteResponse(data);
},
error:
function
(x, y, z) {
alert(x +
'\n'
+ y + '\n' + z);
}
});
}
function
Delete() {
jQuery.support.cors =
true;
var
id = $('#DeletedId').val()
$.ajax({
url:
'http://tes2.test.com/API/api/crmconsts'
+ id,
type:
'DELETE',
contentType:
"application/json;charset=utf-8",
success:
function
(data) {
WriteResponse(data);
},
error:
function
(x, y, z) {
alert(x +
'\n'
+ y + '\n' + z);
}
});
}
function
WriteResponse(crmconsts) {
var
strResult = "<table><th>ID</th><th>OrderBy</th><th>ConstType</th><th>ConstCode</th><th>Detail</th><th>Status</th>";
Which I just changed ForOrigins(“http://test1”). Because it is coming from test1. Then for IIS part I could not figure out , I should put it in mvc project
web.config or web api project web.config ? Suppose it should go to WebAPI project server (test1), am i right?
And do I still add mvc part in the mvc project which host on test1?
You need to use the right interception component and matching configuration. Are you trying to enable CORS for WebAPI? MVC? Or just URLs in IIS (handlers)?
Our target is from our one MVC web application make a call to the WebAPI.
WebAPI and MVC web application were host on different web servers and there is fortigate in between them. MVC web site need get data from Web API and send to Web API. Web API connect to our db to manipulate the data. Actually we treat WebApi same as a web
service.
Ok, so if it's for WebAPI then you only need the RegisterCors helper with the WebApiCorsConfiguration. You do not need the http module in web.config for MVC or IIS. If you're still getting errors, then show the exception callstack info.
You'll have to debug this some more on your end and find out what is fialing and where. IIS might have WebDAV registered so it might be blocking the CORS library. Here are some more links that might help:
moniquema
0 Points
9 Posts
How to access Web API from a website
Jan 31, 2013 10:20 AM|LINK
Currently we create a website using MVC and data layer we would like to use web api and host in different web server.
I meant the website host on one web server, web api will host on another server. We tried to make a call (like asmx service) to manipulate data from Web Api. We tried to use Ajax but could not make it success. And could not find any sample for this or using Httpclient inside mvc site. I’m new for web api. If I’m wrong please correct me. Is there somebody could help me? The following code host on server http://test1/test
@{
ViewBag.Title =
"Home Page";
}
<
script type="text/javascript">
function GetAll() {
jQuery.support.cors =
true;
$.ajax({
url:
'http://tes2.test.com/API/api/crmconsts',
type:
'GET',
dataType:
'json',
success:
function (data) {
WriteResponse(data);
},
error:
function (x, y, z) {
alert(x +
'\n' + y + '\n' + z);
}
});
}
function AddConsts() {
jQuery.support.cors =
true;
var CRMConsts = {
ID:$(
'#id').val(),
OrderBy: $(
'#OrderBy').val(),
ConstType: $(
'#ConstType').val(),
ConstCode: $(
'#ConstCode').val(),
Detail: $(
'#Detail').val(),
Status: $(
'#Status').val()
};
$.ajax({
url:
'http://tes2.test.com/API/api/crmconsts',
type:
'POST',
data: JSON.stringify(CRMConsts),
contentType:
"application/json;charset=utf-8",
success:
function (data) {
WriteResponse(data);
},
error:
function (x, y, z) {
alert(x +
'\n' + y + '\n' + z);
}
});
}
function Delete() {
jQuery.support.cors =
true;
var id = $('#DeletedId').val()
$.ajax({
url:
'http://tes2.test.com/API/api/crmconsts' + id,
type:
'DELETE',
contentType:
"application/json;charset=utf-8",
success:
function (data) {
WriteResponse(data);
},
error:
function (x, y, z) {
alert(x +
'\n' + y + '\n' + z);
}
});
}
function WriteResponse(crmconsts) {
var strResult = "<table><th>ID</th><th>OrderBy</th><th>ConstType</th><th>ConstCode</th><th>Detail</th><th>Status</th>";
$.each(crmconsts,
function (index, crmconsts) {
strResult +=
"<tr><td>" + crmconsts.ID + "</td><td> " + crmconsts.OrderBy + "</td><td>" + crmconsts.ConstType + "</td><td>" + crmconsts.ConstCode + "</td><td>" + crmconsts.Detail + "</td><td>" + crmconsts.Status + "</td></tr>";
});
strResult +=
"</table>";
$(
"#divResult").html(strResult);
}
function ShowCrmConsts(crmconsts) {
if (crmconsts != null) {
var strResult = "<table><th>ID</th><th>OrderBy</th><th>ConstType</th><th>ConstCode</th><th>Detail</th><th>Status</th>";
strResult +=
"<tr><td>" + crmconsts.ID + "</td><td> " + crmconsts.OrderBy + "</td><td>" + crmconsts.ConstType + "</td><td>" + crmconsts.ConstCode + "</td><td>" + crmconsts.Detail + "</td><td>" + crmconsts.Status + "</td></tr>";
strResult +=
"</table>";
$(
"#divResult").html(strResult);
}
else {
$(
"#divResult").html("No Results To Display");
}
}
function GetConst() {
jQuery.support.cors =
true;
var id = $('#Getid').val();
$.ajax({
url:
'http://tes2.test.com/API/api/crmconsts' + id,
type:
'GET',
dataType:
'json',
success:
function (data) {
ShowCrmConsts(data);
},
error:
function (x, y, z) {
alert(x +
'\n' + y + '\n' + z);
}
});
}
</
script>
@section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
<div>
<table><tr>
<td><button onclick="GetAll();return false;">Get All CRMConsts</button></td>
<td>Enter Id: <input type="text" id="Getid" style="width:50PX"/></td>
<td><button onclick="GetConst();return false;">Get CRMConst</button></td>
<td>
<table>
<tr><td> Id:</td><td><input type="text" id="id" /></td></tr>
<tr><td>Order By:</td><td><input type="text" id="OrderBy" /></td></tr>
<tr><td>Const Type:</td><td><input type="text" id="ConstType" /></td></tr>
<tr><td>Const Code:</td><td><input type="text" id="ConstCode" /></td></tr>
<tr><td>Detail:</td><td><input type="text" id="Detail" /></td></tr>
<tr><td>Status:</td><td><input type="text" id="Status" /></td></tr>
</table>
</td>
<td><button onclick="AddConsts();return false;">Add Const</button></td>
<td>Delete<input type="text" id="DeletedId" style="width:50PX"/></td>
<td><button onclick="Delete(); return false;">Delete</button></td>
</tr></table>
</div>
</div>
</section>
}
<
h3>Oputput of action done through WEB API:</h3>
<
ol class="round">
<li>
<div id="divResult"></div>
</li>
</
ol>
BrockAllen
All-Star
28114 Points
4997 Posts
MVP
Re: How to access Web API from a website
Jan 31, 2013 12:46 PM|LINK
You need the WebAPI server to support CORS. Check these links:
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/
http://brockallen.com/2012/10/18/cors-iis-and-webdav/
http://brockallen.com/2012/12/15/cors-and-windows-authentication/
DevelopMentor | http://www.develop.com
thinktecture | http://www.thinktecture.com/
moniquema
0 Points
9 Posts
Re: How to access Web API from a website
Feb 01, 2013 11:03 AM|LINK
Hi Brock,
Thank you very much for your help on this. I have some confuse with the three parts.
I have two IIS server, one for host mvc site, the other is hosting for WebApi. As you recommend,
I added into web api part in WebAPi project (which host on test2)
protected void Application_Start()
{…
CorsConfig.RegisterCors(GlobalConfiguration.Configuration);
}
And then in App_Start/CorsConfig.cs:
public class CorsConfig
{
public static void RegisterCors(HttpConfiguration httpConfig)
{
WebApiCorsConfiguration corsConfig = newWebApiCorsConfiguration();
// this adds the CorsMessageHandler to the HttpConfiguration’s
// MessageHandlers collection
corsConfig.RegisterGlobal(httpConfig);
// this allow all CORS requests to the Products controller
// from the http://foo.com origin.
corsConfig
.ForResources(“Products”)
.ForOrigins(“http://test1”)
.AllowAll();
}
}
Which I just changed ForOrigins(“http://test1”). Because it is coming from test1. Then for IIS part I could not figure out , I should put it in mvc project web.config or web api project web.config ? Suppose it should go to WebAPI project server (test1), am i right?
And do I still add mvc part in the mvc project which host on test1?
Thanks,
moniquema
0 Points
9 Posts
Re: How to access Web API from a website
Feb 01, 2013 11:54 AM|LINK
Hi Brock,
I added following code to WebApi project. Then I got error 500.
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
CorsConfig.RegisterCors(GlobalConfiguration.Configuration);
ConfigureCors(UrlBasedCorsConfiguration.Configuration);
}
void ConfigureCors(CorsConfiguration corsConfig)
{
corsConfig
.ForResources("CRMConsts")
.ForOrigins("http://test1.vgm.com", "http://test2.vgm.com")
.AllowAll();
}
}
Also created a configure class as you suggested:
public static class CorsConfig
{
public static void RegisterCors(HttpConfiguration httpConfig)
{
WebApiCorsConfiguration corsConfig = new WebApiCorsConfiguration();
corsConfig.RegisterGlobal(httpConfig);
corsConfig
.ForResources("CRMConsts")
.ForOrigins("http://test1.vgm.com")
.AllowAll();
}
}
Didn't make any change on mvc project but I got error 500.
moniquema
0 Points
9 Posts
Re: How to access Web API from a website
Feb 01, 2013 12:00 PM|LINK
Sorry. I forgot the web config part. I added following part inside web config and got error 500
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules>
<add name="CorsHttpModule" type="Thinktecture.IdentityModel.Http.Cors.IIS.CorsHttpModule"/>
</modules>
BrockAllen
All-Star
28114 Points
4997 Posts
MVP
Re: How to access Web API from a website
Feb 01, 2013 05:07 PM|LINK
You need to use the right interception component and matching configuration. Are you trying to enable CORS for WebAPI? MVC? Or just URLs in IIS (handlers)?
DevelopMentor | http://www.develop.com
thinktecture | http://www.thinktecture.com/
moniquema
0 Points
9 Posts
Re: How to access Web API from a website
Feb 01, 2013 06:15 PM|LINK
Thank you for your response.
Yes, I'm trying to enable CORS for WebAPI.
Our target is from our one MVC web application make a call to the WebAPI.
WebAPI and MVC web application were host on different web servers and there is fortigate in between them. MVC web site need get data from Web API and send to Web API. Web API connect to our db to manipulate the data. Actually we treat WebApi same as a web service.
Is it possible?
Thank you very much!
BrockAllen
All-Star
28114 Points
4997 Posts
MVP
Re: How to access Web API from a website
Feb 01, 2013 10:39 PM|LINK
Ok, so if it's for WebAPI then you only need the RegisterCors helper with the WebApiCorsConfiguration. You do not need the http module in web.config for MVC or IIS. If you're still getting errors, then show the exception callstack info.
DevelopMentor | http://www.develop.com
thinktecture | http://www.thinktecture.com/
moniquema
0 Points
9 Posts
Re: How to access Web API from a website
Feb 04, 2013 01:54 PM|LINK
Hi Brock,
Thanks, I still could not make it work.
I based on the sample you offered on the internet. “Thinktecture.IdentityModel.45-master”
Added class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using Thinktecture.IdentityModel.Http.Cors.WebApi;
namespace WebApi_Cors_v01
{
public class CorsConfig
{
public static void RegisterCors(HttpConfiguration httpConfig)
{
WebApiCorsConfiguration corsConfig = new WebApiCorsConfiguration();
// this adds the CorsMessageHandler to the HttpConfiguration’s
// MessageHandlers collection
corsConfig.RegisterGlobal(httpConfig);
// this allow all CORS requests to the Products controller
// from the http://foo.com origin.
corsConfig
.ForResources("CRMConsts")
.ForOrigins("http://test1.vgm.com/")//http://localhost") // http://test2.vgm.com
.AllowAllMethods()
.AllowAll();
}
}
}
Register in global.asax
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
CorsConfig.RegisterCors(GlobalConfiguration.Configuration);
}
}
Added line in web.config
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
Changed in web.config
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true"/>
<!--<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>-->
</system.webServer>
That’s all I did. If I added from localhost, it worked fine but if I put from “test1”, it’s failed. The error message is no transport.
By the way, how to make cors work with IE9. Could you please give me some idea or sample for it?
Thanks,
BrockAllen
All-Star
28114 Points
4997 Posts
MVP
Re: How to access Web API from a website
Feb 04, 2013 03:31 PM|LINK
You'll have to debug this some more on your end and find out what is fialing and where. IIS might have WebDAV registered so it might be blocking the CORS library. Here are some more links that might help:
http://brockallen.com/category/cors/
DevelopMentor | http://www.develop.com
thinktecture | http://www.thinktecture.com/