GVKun编程网logo

ASP.NET Core WebAPI:不支持的媒体类型 - HTTP 415(不支持的媒体文件类型)

16

在本文中,我们将给您介绍关于ASP.NETCoreWebAPI:不支持的媒体类型-HTTP415的详细内容,并且为您解答不支持的媒体文件类型的相关问题,此外,我们还将为您提供关于415SpringMV

在本文中,我们将给您介绍关于ASP.NET Core WebAPI:不支持的媒体类型 - HTTP 415的详细内容,并且为您解答不支持的媒体文件类型的相关问题,此外,我们还将为您提供关于415 Spring MVC和Rest Service不支持的媒体类型、415不支持的媒体类型-lightswitch 2012中的POST json到OData服务、415不支持的媒体类型; Angular2到API、415不支持的媒体类型jQuery Ajax的知识。

本文目录一览:

ASP.NET Core WebAPI:不支持的媒体类型 - HTTP 415(不支持的媒体文件类型)

ASP.NET Core WebAPI:不支持的媒体类型 - HTTP 415(不支持的媒体文件类型)

如何解决ASP.NET Core WebAPI:不支持的媒体类型 - HTTP 415?

我尝试创建一个新部门,但出现此错误:

{
    "type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"|3361f693-4c3294040da78eae."
}  

谁能告诉我为什么会出现这个错误?我也不能对部门做其他粗鲁的操作。

这是我的部门主管

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DepartmentsController : Controller
    {
        private readonly EmployeeDbContext _context;

        public DepartmentsController(EmployeeDbContext context)
        {
            _context = context;
        }

        // GET: Departments
        [HttpGet]
        public async Task<IActionResult> Index(string sortOrder,string currentFilter,string searchString,int? pageNumber)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
     
            if (searchString != null)
            {
                pageNumber = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewData["CurrentFilter"] = searchString;

            var departments = from d in _context.Departments
                              select d;

            if (!String.IsNullOrEmpty(searchString))
            {
                departments = departments.Where(d => d.departmentName.Contains(searchString)
                               || d.departmentName.Contains(searchString));
            }

            int pageSize = 3;

            return View(await PaginatedList<Department>.CreateAsync(departments.AsNoTracking(),pageNumber ?? 1,pageSize));
        }

        // GET: Departments/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var department = await _context.Departments
                .FirstOrDefaultAsync(m => m.Id == id);

            if (department == null)
            {
                return NotFound();
            }

            return View(department);
        }

        // GET: Departments/Create
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost,ActionName("Create")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("departmentName")] Department department)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(department);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
            }
            catch (dbupdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("","Unable to save changes. " +
                    "Try again,and if the problem persists " +
                    "see your system administrator.");
            }

            return View(department);
        }

        // GET: Departments/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var department = await _context.Departments.FindAsync(id);

            if (department == null)
            {
                return NotFound();
            }

            return View(department);
        }

        // POST: Departments/Edit/5
        // To protect from overposting attacks,enable the specific properties you want to bind to,for 
        // more details,see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost,ActionName("Edit")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id,[Bind("Id,departmentName")] Department department)
        {
            if (id != department.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(department);
                    await _context.SaveChangesAsync();
                }
                catch (dbupdateConcurrencyException)
                {
                    if (!DepartmentExists(department.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }

                return RedirectToAction(nameof(Index));
            }

            return View(department);
        }

        // GET: Departments/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var department = await _context.Departments
                .FirstOrDefaultAsync(m => m.Id == id);

            if (department == null)
            {
                return NotFound();
            }

            return View(department);
        }

        // POST: Departments/Delete/5
        [HttpPost,ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var department = await _context.Departments.FindAsync(id);
            _context.Departments.Remove(department);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool DepartmentExists(int id)
        {
            return _context.Departments.Any(e => e.Id == id);
        }
    }
}

这是我的 Department 模型类:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.Models
{
    public class Department
    {
        [Key]
        public int Id { get; set; }

        [required(ErrorMessage = "Please enter Department Name")]
        [display(Name = "Department Name")]
        public String departmentName { get; set; }

        // Navigation Properties
        public ICollection<Employee> Employees { get; set; }
    }
}

创建视图

@Sergey `@model WebAPI.Models.Department

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Department</h4>
<hr />
<div>
    <div>
        <form asp-action="Create" >
            <div asp-validation-summary="ModelOnly"></div>
            <div>
                <label asp-for="departmentName"></label>
                <input asp-for="departmentName"/>
                <span asp-validation-for="departmentName"></span>
            </div>
            <div>
                <input type="submit" value="Create"/>
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
    @* <a asp-action="Index">Back to List</a>*@
</div>

@section Scripts {
    <script>
        // Add the following code if you want the name of the file appear on select
        $(".custom-file-input").on("change",function () {
            var fileName = $(this).val().split("\\").pop();
            $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
        });
    </script>
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
`

解决方法

删除 [ApiController] 并修复控制器操作:

       [HttpGet]
        public IActionResult Create()
        {
            var model=new Department();
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create( Department department)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(department);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("","Unable to save changes. " +
                    "Try again,and if the problem persists " +
                    "see your system administrator.");
            }

            return View(department);
        }

并查看

<form asp-action="Create" asp-controller"Departments" "method="post" >
 <div asp-validation-summary="ModelOnly"></div>
  <input type="hidden" asp-for="Id" value="@Model.Id" />
            .....
        </form>

415 Spring MVC和Rest Service不支持的媒体类型

415 Spring MVC和Rest Service不支持的媒体类型

我正进入(状态

415 Unsupported Media Type - The server refused this request because the request entity is in a format not supported by the requested resource for the requested method

请求网址为:

http://localhost:8080/ngdemo/web/posts/review/80a5d7660cdb82a8ef9f8db79bb3c8ab14555377

从弹簧控制器读取时出错;我检查了其他具有相同模式的控制器方法,它们工作正常,但不是我新介绍的这种方法。我找不到任何问题,能否请您提出我所缺少的内容?

我的控制器:

@RequestMapping(value = "/review/{key}", method = RequestMethod.GET,  consumes = "", produces = "application/json")public@ResponseBodyList<Review> reviews(@PathVariable(value = "key") String key) {    System.out.println("key : " + key);    List<Review> reviewList = reviewService.getReviewsById(key);    System.out.println("reviewList : " + reviewList.size());    return reviewList;}

我的Angular Services.js:

services.factory(''PostFactory'', [''$resource'', function ($resource) {alert("I am here service");return  {    postmain: $resource(''/ngdemo/web/posts'', {}, {        query: {method: ''GET'', isArray: true },        create: {method: ''POST''}    }),    reviews: $resource(''/ngdemo/web/posts/review/:key'', {}, {        query: {method: ''GET'', params: {key: ''@key''} },        create: {method: ''POST''}    }),    postreview: $resource(''/ngdemo/web/posts/getreview'', {}, {        query: {method: ''GET'', isArray: true },        create: {method: ''POST''}    }),    allresults: $resource(''/ngdemo/web/posts/result/:tag'', {}, {        query: {method: ''GET'', params: {tag: ''@tag''} },        create: {method: ''POST''}    })};

}]);

我的controller.js中的代码可以调用:

var reviewId = place.id;$scope.allreviews = PostFactory.reviews.query({key: reviewId})

我找不到问题出在哪里,所以请大家看看并指出我想念的是什么?谢谢!

答案1

小编典典

它通过添加以下内容起作用:

 @Consumes("text/html") @Consumes("text/html")@RequestMapping(value = "/review/{key}", method = RequestMethod.GET, produces =   "application/json")public@ResponseBodyList<Review> reviews(@PathVariable(value = "key") String key) {

415不支持的媒体类型-lightswitch 2012中的POST json到OData服务

415不支持的媒体类型-lightswitch 2012中的POST json到OData服务

使用JSON发布到OData服务时,出现“错误415:不支持的媒体类型”。

解决方案位于此较长文章的底部。

我可以使用JSON进行获取,但是一旦尝试POST,我就会收到此错误。

我也可以使用XML进行GET / POST,但是我需要使用json。

我认为此错误是指我的标头中的某些内容,而不是我的请求正文的json格式(在下面也可能是错误的),我尝试了多种变体导致相同的错误。

我一直在尝试使用Fiddler进行调试,以下是结果。

JSON开机自检

请求

POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1
User-Agent: Fiddler
Host: scdb38:8888
Content-Length: 91
Accept: application/json;odata=verbose;
Content-Type: application/json;

{
   "d":[
      {
         "Name":"Great White ","Food":"Surfers"
      }
   ]
}

响应

HTTP/1.1 415 Unsupported Media Type
Cache-Control: private
Content-Length: 186
Content-Type: application/json;odata=verbose;charset=utf-8
Server: Microsoft-IIS/7.5
X-Content-Type-Options: nosniff
DataServiceVersion: 1.0;
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed,16 Oct 2013 06:20:10 GMT

{"error":{"code":"1","message":{"lang":"en-AU","value":"<?xml version=\"1.0\" encoding=\"utf-16\"?><ExceptionInfo><Message>Unsupported media type requested.</Message></ExceptionInfo>"}}}

JSON GET

请求标题

GET http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1
User-Agent: Fiddler
Host: scdb38:8888
Content-Length: 0
Accept: application/json;odata=verbose;
Content-Type: application/json;

响应头

HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 591
Content-Type: application/json;odata=verbose;charset=utf-8
Server: Microsoft-IIS/7.5
X-Content-Type-Options: nosniff
DataServiceVersion: 1.0;
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed,16 Oct 2013 06:23:41 GMT

{"d":[{"__metadata":{"id":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(1)","uri":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(1)","etag":"W/\"X'00000000000007E4'\"","type":"LightSwitchApplication.Shark"},"Id":1,"RowVersion":"AAAAAAAAB+Q=","Name":"Tiger Shark","Food":"Penguins"},{"__metadata":{"id":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(2)","uri":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(2)","etag":"W/\"X'00000000000007E5'\"","Id":2,"RowVersion":"AAAAAAAAB+U=","Name":"Grey Nurse","Food":"Lettuce"}]}

我不太明白为什么GET可以正常工作时POST不支持媒体类型的原因。我意识到我正在使用DataServiceVersion:1.0并已查找升级,但是我正在使用LightSwitch
2012并在引用新版本时遇到问题,而又没有破坏LightSwitch应用程序。我认为LightSwitch
2013使用的是较新的版本(?),但是对我而言,升级带来了新的(非技术性)挑战。我感觉自己正在绕过圈子,这是我的最后选择,与同事交谈后,我唯一的失败选择是在数据库上创建数据模型并在此数据库上创建OData服务。

-— 更新 -—

此后,我尝试了Jen S提供的两个修复程序,现在得到错误:400错误的请求。

使用odata = verbose

POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1
Accept: application/json;odata=verbose;
Content-Type: application/json;odata=verbose;
Content-Length: 98
Host: scdb38:8888

{
   "d":[
      {
         "Name":"Great White ","Food":"Surfers"
      }
   ]
}


HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Length: 201
Content-Type: application/json;odata=verbose;charset=utf-8
Server: Microsoft-IIS/7.5
X-Content-Type-Options: nosniff
DataServiceVersion: 1.0;
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed,16 Oct 2013 23:31:09 GMT

{"error":{"code":"1","value":"<?xml version=\"1.0\" encoding=\"utf-16\"?><ExceptionInfo><Message>An error occurred while processing this request.</Message></ExceptionInfo>"}}}

使用DataServiceVersion:1.0

POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1
Accept: application/json;odata=verbose;
Content-Type: application/json;
Content-Length: 98
Host: scdb38:8888
DataServiceVersion: 1.0;

{
   "d":[
      {
         "Name":"Great White ","value":"<?xml version=\"1.0\" encoding=\"utf-16\"?><ExceptionInfo><Message>An error occurred while processing this request.</Message></ExceptionInfo>"}}}

使用WebServiceVerion:2.0

POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1
Accept: application/json;odata=verbose;
Content-Type: application/json;
Content-Length: 98
Host: scdb38:8888
DataServiceVersion: 2.0;

{
   "d":[
      {
         "Name":"Great White ","Food":"Surfers"
      }
   ]
}

HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Length: 201
Content-Type: application/json;odata=verbose;charset=utf-8
Server: Microsoft-IIS/7.5
X-Content-Type-Options: nosniff
DataServiceVersion: 1.0;
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed,16 Oct 2013 23:38:23 GMT

{"error":{"code":"1","value":"<?xml version=\"1.0\" encoding=\"utf-16\"?><ExceptionInfo><Message>An error occurred while processing this request.</Message></ExceptionInfo>"}}}

我是否正在解决这个问题,这仅仅是JSON请求主体结构不正确的问题吗?我尝试了几次尝试都没有成功,但是使用XML进行发布是可行的。

----- 解决方案 ------

感谢Jen的帮助,使用json格式向OData服务发布对我来说很有效。

POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1
Accept: application/json;odata=verbose;
Content-Type: application/json;
Content-Length: 62
Host: scdb38:8888
DataServiceVersion: 1.0;


 {
    "Name":"Great White ","Food":"Surfers"
 }


HTTP/1.1 201 Created
Cache-Control: no-cache
Content-Length: 298
Content-Type: application/json;odata=verbose;charset=utf-8
ETag: W/"X'00000000000007E7'"
Location: http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(4)
Server: Microsoft-IIS/7.5
X-Content-Type-Options: nosniff
DataServiceVersion: 1.0;
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu,17 Oct 2013 23:22:12 GMT

{"d":{"__metadata":{"id":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(4)","uri":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(4)","etag":"W/\"X'00000000000007E7'\"","Id":4,"RowVersion":"AAAAAAAAB+c=","Name":"Great White ","Food":"Surfers"}}

415不支持的媒体类型; Angular2到API

415不支持的媒体类型; Angular2到API

我是角度2的新手,我遇到了一个无法找到解决方案的问题:
当我尝试从角度2发布到API我得到 – 415不支持的媒体类型.

Angular 2代码:

onSubmit(value: any) {
    // console.log(value.message);
    let headers = new Headers({ 'Content-Type': 'application/json'});
    let options = new RequestOptions({ headers: headers });
    let creds = 'statusukNown';
    let body = JSON.stringify(creds);
    this.http.post('http://localhost:1318/api/ActionItem',creds)
      .subscribe(
        () => {console.log('Success')},err => {console.error(err)}
      );
  }

我的控制器代码:

// POST api/actionitem
        [HttpPost]
        public ActionItem Post( [FromBody]string str)// _id,string _status)
        {
            ActionItem item = new ActionItem( 313,str);
            return item;
        }

当我将控制器代码更改为不从主体获取数据时,它可以工作但是引用NULL.

我的API调用截图:

enter image description here


请帮助&如果需要更多细节,请告诉我.

解决方法

enter image description here

您定义了标题,但没有使用它.将您的代码更改为

this.http.post('http://localhost:1318/api/ActionItem',body,options).map(response => response.json())
      .subscribe(
        () => {console.log('Success')}
      );

415不支持的媒体类型jQuery Ajax

415不支持的媒体类型jQuery Ajax

我正在使用Maven Rest API。通过jQuery Ajax调用发出POST请求时,出现415错误。请看一下我的代码。

function getUserDetails() {
  var name = $("#name").val();
  var mobile = $("#mobile").val();
  var location = $("#location").val();
  var email = $("#email").val();

  var userDetails = {
    "name": name,"mobile": mobile,"email": email,"location": location
  };

  return userDetails;
}

function createuser() {
  sendRequest("registerProcess",getUserDetails(),"post");
}

function sendRequest(url,input,method) {
  $.ajax({
    url: url,async: false,data: JSON.stringify(input),error: function(response) {
      //displayResponseMessage(response);
      console.log("Error");
    },success: function(response) {
      console.log(" Successfull");
    },type: method,headers: {
      Accept: 'application/json;charset=utf-8',contentType: 'application/json;charset=utf-8'
    },dataType: 'json'
  });
}

这是我的控制器。这UserForm是POJO类别

@RequestMapping(value = "/registerProcess",method = RequestMethod.POST,consumes= MediaType.APPLICATION_JSON_VALUE)
public String addUser(@RequestBody UserForm user) 
{  
  System.out.println("Inside Controller" );
  String email = user.getEmail();
  String mobile = user.getMobile();
  System.out.println("Details :" + email + mobile);
  return "welcome";
}

提前致谢

关于ASP.NET Core WebAPI:不支持的媒体类型 - HTTP 415不支持的媒体文件类型的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于415 Spring MVC和Rest Service不支持的媒体类型、415不支持的媒体类型-lightswitch 2012中的POST json到OData服务、415不支持的媒体类型; Angular2到API、415不支持的媒体类型jQuery Ajax的相关知识,请在本站寻找。

本文标签: