2017-11-15 2 views
0

Ich bin Neuling in Angular 2. Ich sende Formdaten von eckigen 2 zu Webapi, aber es funktioniert nicht. WebAPI:. Net WebAPI Post Methode funktioniert nicht von Angular2 Service

public class FetchDataController : ApiController 
    { 

     [HttpGet] 
     public IList<Student> ListOfStudents() 
     { 
      AppRepository objapp = new AppRepository(); 
      IList<Student> objData = null; 
      objData = objapp.getStudent(); 
      return objData; 
     } 

     [HttpPost] 
     [Route("PostStudent")] 
     public JsonResult<Boolean> PostStudent(Student value) 
     { 
      // Append text to an existing file named "WriteLines.txt". 
      string data = "ID: " + value.Id + ", FirstName: " + value.FirstName + ",LastName: " + value.LastName + ",Salary: " + value.salary; 
      using (StreamWriter outputFile = new StreamWriter(HttpContext.Current.Server.MapPath("~")+ "/TestVD/WriteLines.txt", true)) 
      { 
       outputFile.WriteLine(data); 
      } 
      return Json(true); 
     } 

    } 

ist mein WebAPIConfig.js wie folgt. Ich habe CORS hinzugefügt sowie Webconfig Datei hier Handhabung:

var cors = new EnableCorsAttribute("http://localhost", "*", "*"); 
       config.EnableCors(cors); 

      // Web API configuration and services 
      config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); 
      // Web API routes 
      config.MapHttpAttributeRoutes(); 
      config.Routes.MapHttpRoute(
      name: "ListOfStudents", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { controller = "FetchData", action = "ListOfStudents", id = RouteParameter.Optional } 
      ); 

      config.Routes.MapHttpRoute(
       name: "PostStudent", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { controller = "FetchData", action = "PostStudent", id = RouteParameter.Optional } 
      ); 
      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 

Nun Von Angular 2, ich bin in der Lage Daten zu zeigen, von Studenten WebAPI Methode Liste, aber während Posting Ich erhalte „405 (Methode nicht erlaubt) "von meiner WEBAPI-URL. Ich bin unten Antwort von WEBAPI Post-Methode gettling.

ok 
: 
false 
status 
: 
405 
statusText 
: 
"Method Not Allowed" 
type 
: 
2 
url 
: 
"http://localhost/TestWebService/api/FetchData/" 
_body 
: 
"{"Message":"The requested resource does not support http method 'POST'."}" 

Mein Angular 2 Service-Code ist wie folgt

@Injectable() 
export class RssService { 
private studentUrl = "http://localhost/TestWebService/api/FetchData/"; 
    constructor(private http: Http) { } 
    getStudentList() { 
     return this.http.get(this.studentUrl) 
      .map(res => <Student[]>res.json()) 
      .catch(this.handleError); 
    } 
    private handleError(error: Response) { 
     console.error(error); 
     return Observable.throw(error.json().error || 'Server error'); 
    } 
    postStudent(model: any): Observable<any> { 
     let body = JSON.stringify(model); 
     let headers = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: headers }); 
     console.log('add Student start : ' + body); 
     return this.http.post(this.studentUrl , body, options) 
      .map((response: Response) => <any>response.json()) 
      .catch(this.handleError); 
    } 
} 

Könnten Sie mir bitte helfen ...

Antwort

0

Sie haben ein Routing-Attribut [Route("PostStudent")] auf Ihrer PostStudent Methode.

Aus diesem Grund ist die URL für diese Aktion nicht http://localhost/TestWebService/api/FetchData/, sondern http://localhost/TestWebService/PostStudent.

Um die URL http://localhost/TestWebService/api/FetchData/ zu verwenden, entfernen Sie einfach dieses Route Attribut.

Wenn Sie noch bestimmte Route für PostStudent Aktion verwenden möchten, und Zugriff auf sie über http://localhost/TestWebService/api/FetchData/PostStudent, fügen Sie auch RoutePrefix Attribut auf dem Controller:

[RoutePrefix("api/FetchData")] 
public class FetchDataController : ApiController 

Überprüfen dieser Artikel für Modus Details: Attribute Routing in ASP.NET Web API 2

0

Ich habe Es wurde aufgrund des System.Net- und System.Web-Namespace aufgelöst. Diese link helfen mir sehr.

Verwandte Themen