2015-07-21 77 views
0

我正在尝试创建一个自托管服务作为我的日志在我的应用程序的中心点。所以我在OWIN中创建自己托管的服务并安装了我的服务。该服务工作正常,我可以通过JQuery通过AJAX调用使其通过GET方法工作。我的问题来自POST方法,因为我想将很多字段发布到WEB API(最好是一个包含所有内容的对象),但它根本不起作用...并且我收到此错误消息自己托管OWIN与CORS的WEB API

415 - >“不支持的媒体类型”

“请求包含一个实体主体但没有Content-Type标头,该资源不支持推断的媒体类型'application/octet-stream'”,“ExceptionMessage”:“没有MediaTypeFormatter可用于从媒体类型为'application/octet-stream'的内容读取'Log'类型的对象。“,”ExceptionType“:”System.Net.Http.UnsupportedMediaTypeException“,”StackTrace“:”at System。 Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent content,Type type,IEnumerable'1 formatters,IFormatterL ogger formatterLogger,的CancellationToken的CancellationToken个)\ r \ n在System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage请求,类型类型,IEnumerable`1格式化,IFormatterLogger formatterLogger,的CancellationToken的CancellationToken)”

我可以发送一个POST没有参数,它的工作......但我需要这些参数!

这里是我的代码:

Log类

public class Log 
{ 
    public string Message { get; set; } 
    public string ApplicationName { get; set; } 
} 

WEB API控制器

public class MessagingController : ApiController 
{ 
    [HttpPost] 
    public void Log([FromBody] Log log) 
    { 
     var path = Program.ConfigurationService.GetConfigValue(ConfigurationService.RootPathConfig); 

     using (var writter = new StreamWriter(path + "TEST.txt")) 
     { 
      writter.Write(log.ApplicationName + " -> " + log.Message); 
     } 
    } 
} 

AJAX调用Web API

var obj = { 
     applicationName: "APP", 
     message: "MESS" 
    } 

    $.ajax({ 
     type: "POST", 
     cache: false, 
     url: "http://localhost:9001/api/messaging/log", 
     data: JSON.stringify(obj), 
     dataType: 'json', 
     contentType: "application/json; charset=utf-8; Access-Control-Allow-Origin;", 
     async: true, 
     success: function(resp) { 
      console.log(resp); 
     }, 
     error: function(err) { 
      console.log(err); 
     } 
    }); 

回答

1

好吧,我发现我的在本教程中回答!

http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En

我删除了AJAX请求的萨姆数据,现在它完美地做自己的工作!

这是我的新的AJAX:

var obj = { 
    applicationName: "APP", 
    message: "MESS" 
} 

$.ajax({ 
    type: "POST", 
    url: "http://localhost:9001/api/messaging/log", 
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", 
    data: obj, 
    success: function(resp) { 
     console.log(resp); 
    }, 
    error: function(err) { 
     console.log(err); 
    } 
}); 

确定使用Fiddler我发现他,我是需要真正的ContentType是:

的contentType:“应用程序/ x-WWW的形式,进行了urlencoded;字符集= UTF-8“,

相关问题